package com.cloud.tool.exception;

import com.cloud.tool.common.RemoteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author WangZY
 * @Date 2022/4/14 11:02
 * @Description 全局异常监听类
 **/
@RestControllerAdvice
@Slf4j
public class ToolExceptionHandler {
    /**
     * @Author WangZY
     * @Date 2020/12/24 10:40
     * @Description 全局异常监听
     **/
    @ExceptionHandler(Exception.class)
    public RemoteResult<String> handleException(HttpServletRequest request, Exception e) {
        log.error("全局监听异常捕获,方法={}", request.getRequestURI(), e);
        return new RemoteResult<>("10001", "内部错误，请联系管理员处理");
    }

    @ExceptionHandler(AbstractException.class)
    public RemoteResult<String> handleBusinessException(HttpServletRequest request, AbstractException e) {
        log.error("全局监听业务异常捕获,方法={}", request.getRequestURI(), e);
        return new RemoteResult<>(e.getErrCode(), e.getErrMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RemoteResult<String> methodArgumentNotValidExceptionHandler(HttpServletRequest request,
                                                                       MethodArgumentNotValidException e) {
        log.error("全局监听Spring-Valid异常捕获,方法={}", request.getRequestURI(), e);
        // 从异常对象中拿到ObjectError对象
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String err = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        // 然后提取错误提示信息进行返回
        return new RemoteResult<>("10001", err);
    }
}
